package org.example.controller;

import org.example.model.User;
import org.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.net.ssl.HandshakeCompletedEvent;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/list")
    public Object list(){
        List<User> users = userService.list();
        return users;
    }

    @RequestMapping("/list2")
    public Object list2(){
        List<User> users = userService.list2();
        return users;
    }
    
    @RequestMapping("/insert1")
    public Object insert1(String username, String password){
        int n = userService.insert1(username, password);
        return null;
    }

    @RequestMapping("/insert2")
    public Object insert2(User user){
        int n = userService.insert2(user);
        return null;
    }

    @RequestMapping("/queryByGithub")
    public Object queryByGithub(String github){
        List<User> users = userService.queryByGithub(github);
        return users;
    }

    @RequestMapping("/update")
    public Object update(User user){
        int n = userService.update(user);
        return null;
    }

    @RequestMapping("/deleteByNickname")
    public Object deleteByNickname(String nickname){
        int n = userService.deleteByNickname(nickname);
        return null;
    }

    @RequestMapping("/selectOrderBy")
    public Object selectOrderBy(String columnName, String orderBy){
        List<User> users = userService.selectOrderBy(columnName, orderBy);
        return users;
    }

    @RequestMapping("/selectList")
    public Object selectList(String nickname){
        List<User> users = userService.selectList(nickname);
        return users;
    }

    @RequestMapping("/1tom")
    public Object oneToMany(){
        List<User> users = userService.selectOneToMany();
        return users;
    }

    @RequestMapping("/login")
    public Object login(User user,
                        HttpServletRequest req){
        User exist = userService.selectOne(user);
        Map<String, Object> map = new HashMap<>();
        if(exist == null){//账号密码错误
            map.put("ok", false);
            map.put("msg", "账号密码错误");
        }else {
            map.put("ok", true);
            map.put("msg", "登录成功");
            //创建session，并保存用户信息
            HttpSession session = req.getSession();
            session.setAttribute("user",exist);
        }
        return map;
    }
}
